<?php

namespace app\wechat\controller;

use app\api\model\dealer\Referee as RefereeModel;
use app\api\model\User;
use app\common\exception\BaseException;
use EasyWeChat\Factory;
use think\Cache;
use think\Controller;
use app\common\model\WxappMchi as WxappMchiModel;
use think\Db;
use think\Validate;

/**
 * 微信
 * Class Index
 * @package app\store\controller
 */
class Index extends Controller
{
    /**
     * 后台首页
     * @return mixed
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function index()
    {
        $order_id = input('order_id');

        $app = Factory::officialAccount(config("wechat_easy"));
        $oauth = $app->oauth;
        $wxuser = session('wechat_user');

        if(!empty($order_id)){
            session('order_id', $order_id);
        }

      // if (empty($wxuser)) {
            session('target_url', $_SERVER['PATH_INFO']);

            return $oauth->redirect()->send();
       // }

        $model = WxappMchiModel::detail();

        return $this->fetch('index', compact('model'));
    }

    public function callback()
    {
        $app = Factory::officialAccount(config("wechat_easy"));
        $oauth = $app->oauth;

        $user = $oauth->user();

        session('wechat_user', $user->toArray());

        $user_arr = $user->toArray();

        $order_id = session('order_id');
        if(!empty($order_id)){
            $order_info = Db::name('appointment_order')->where(['order_id'=>$order_id])->find();

            if(!$order_info){
                $this->error('线下订单不存在');
            }

            $check = Db::name('user')->where(['open_id'=>$user_arr['id']])->find();
            if($check){

                Db::name('appointment_order')->where(['order_id'=>$order_id])->update(['user_id'=>$check['user_id']]);
                Cache::set($check['open_id'].'_order_id',$order_id,3600);
            }else{

                $user_arr['nickname'] = preg_replace_callback('/./u',function(array $match){
                    return strlen($match[0]) >= 4 ? '' : $match[0];
                },$user_arr['nickname']);

                $data = [
                    'nickName'=>$user_arr['nickname'],
                    'avatarUrl'=>$user_arr['avatar'],
                ];

                $model = new User;

                $res = $model->allowField(true)->save(array_merge($data, [
                    'open_id' => $user_arr['id'],
                    'wxapp_id' => $order_info['wxapp_id']
                ]));

                if(!$res){
                    $this->error('注册失败');
                }

                Db::name('appointment_order')->where(['order_id'=>$order_id])->update(['user_id'=>$model['user_id']]);
                Cache::set($user_arr['id'].'_order_id',$order_id,3600);
            }
        }
//        log_print(Cache::get($user_arr['id'].'_order_id'));
        session('order_id', '');
        $targetUrl = session('target_url');

        $model = WxappMchiModel::detail();

        return $this->fetch('index', compact('model'));
        $this->redirect($targetUrl);
    }

    /*
     * 公众号自定义菜单
     */
    public function menu()
    {
        var_dump(config("wechat_easy"));
        $app = Factory::officialAccount(config("wechat_easy"));
        $app->menu->delete();
        $buttons = [
            [
                "type" => "miniprogram",
                "name" => "预订服务",
                "appid"=>config("wechat.mini_appid"),
                'pagepath'=>'pages/index/index',
                'url'=>"http://mp.weixin.qq.com"
            ],
            [
                "type" => "miniprogram",
                "name" => "自助预约",
                "appid"=>config("wechat.mini_appid"),
                'pagepath'=>'pages/yuyue/order',
                'url'=>"http://mp.weixin.qq.com"
            ],
            [
                "type" => "miniprogram",
                "name" => "个人中心",
                "appid"=>config("wechat.mini_appid"),
                'pagepath'=>'pages/user/index',
                'url'=>"http://mp.weixin.qq.com"
            ],
        ];

        $res = $app->menu->create($buttons);
        var_dump($res);
        $list = $app->menu->current();
        var_dump($list);
        $user = $app->menu->match('oSpgC0YpIm9bA3Skm_ajOQv8ZWms');
        var_dump($user);
    }


    /*
     * 公众号携带参数
     */
    public function QRCode()
    {
        $order_id = input('order_id');

        $app = Factory::officialAccount(config("wechat_easy"));

        $accessToken = $app->access_token;

        $token = $accessToken->getToken();

        $url = 'https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=' . $token['access_token'];

        $params = [
            'expire_seconds' =>    60488,
            'action_name'   => 'QR_SCENE',
            'action_info'   => [
                'scene' => ['scene_id'=>$order_id]
            ]
        ];

        $response = posturl($url, $params);
        if($response['ticket']){
            $url = 'https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket='.urlencode($response['ticket']);
            $code = doCurlGetRequest($url);
            $path = 'uploads/code/' . date('Ymd') . '/';
            if (!is_dir($path)) mkdir($path, 0777, true);
            $file = $path . 'qr' . $order_id . '_' . time() . '.png';

            file_put_contents($file, $code);
            $url = base_url().'/' . $file;
            $data = [
                'code'=>1,
                'url'=>$url
            ];
            return json($data);
        }
    }
}
